// textarea
const editor = new TE(document.querySelector('textarea'));

$(function() {
    $('#submitButton').click(function() {
        let data = new FormData(document.getElementById('post-form'));
        $.ajaxSetup({
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            }
        });
        ajax('/post/submit', data, function(res) {
            if (res.status === 'success') {
                toast.success(res.message, 3000);
                setTimeout(function() {
                    location.reload();
                }, 1500);
            } else {
                toast.error(res.message, 3000);
            }
        });
    });
});

/**
 * 计算阅读所需时间，按照每分钟 250 字计算
 */
// 统计文章字数
const content = document.querySelector('#postContent');
const numWords = getStringLength(content.textContent);
// 每分钟字数
const readingSpeed = 250;
const readingTime = Math.ceil(numWords / readingSpeed);
// 计算阅读时间
const readingTimeEle = document.querySelector('#readingTime');
readingTimeEle.textContent = `${readingTime} 分钟`;

/**
 * 点击图片自动切换下一张
 */
(function () {
    let container = document.getElementById("jsSwitchNext");
    let images    = container.getElementsByTagName("img");
    let nav       = document.getElementById("jsSwitchNav");
    let links     = nav.getElementsByTagName("a");
    let current   = 0;

    // 单击图像，显示下一个图像
    container.addEventListener("click", function (e) {
      e.preventDefault();
      showImage((current + 1) % images.length);
    });

    // 单击链接，显示相应的图像
    for (let i = 0; i < links.length; i++) {
      links[i].addEventListener("click", function (e) {
        e.preventDefault();
        showImage(i);
      });
    }

    showImage(0);

    function showImage(index) {
      images[current].classList.add("hidden");
      images[index].classList.remove("hidden");
      links[current].classList.remove("active");
      links[index].classList.add("active");
      current = index;
    }
})();